package com.wanbatv.wanba.jianshencao.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.wanbatv.wanba.jianshencao.R;
import com.wanbatv.wanba.jianshencao.util.AppUtil;
import com.wanbatv.wanba.jianshencao.util.Behavior;
import com.wanbatv.wanba.jianshencao.util.Crypto;
import com.wanbatv.wanba.jianshencao.util.DataReport;
import com.wanbatv.wanba.jianshencao.util.ProductInfo;
import com.wanbatv.wanba.jianshencao.util.Util;
import com.wanbatv.wanba.jianshencao.util.WanbaMediaPlayer;
import com.wanbatv.wanba.jianshencao.utils.Product;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import cn.ffcs.itvpay.ItvPayTask;
import de.hdodenhof.circleimageview.CircleImageView;



/**
 * 全屏播放器
 * 
 * @author zhangyus
 *
 */
public class SimplePlayerActivity extends FullScreenActivity implements
		OnPreparedListener, OnInfoListener,MediaPlayer.OnErrorListener {

	//标记快进快退按键状态：正常，未进行快进快退操作
	private static final int STATE_FAST_SEEK_IDLE = 0;
	//标记快进快退按键状态：用户长按着按键，但还未开始快进快退
	private static final int STATE_FAST_SEEK_PREPARED = 1;
	//标记快进快退按键状态：已经开始快进快退
	private static final int STATE_FAST_SEEK_START = 2;
//	MediaController mc;
	VideoView mVideoView;
	private long exitTime;
	ProgressDialog dialog2;
	SurfaceView surfaceView;
	String appName;
	String loading;
	String exitInfo;

	View bofangView;
	ImageView playStat;
	ImageView playStop;
	ImageView playBack;
	ImageView playGo;
	ProgressBar playprogressbar;
	Thread mThread;
	private boolean isRunning = true;
	WanbaMediaPlayer mediaPlayer=null;
	ProgressBar progressBar;
	TextView carlorie;
	static float kaluli = 0.0f;
	static int duration=0;
	static String device_id = Build.SERIAL;
	static  int region= ProductInfo.getInstance().region;
	static String title=null;
	static  int emoji=1;

	private static final int MSG_PLAY_PROGRESS = 1;
	private static final int PLAY_MESSAGE=2;

	private int mContentCode = 0;
	private int mCateCode = 0;
	private String mCateName = "";
	private String mTitle = "";

	private boolean LEFT_ON=false;
	private boolean RIGHT_ON=false;

	private boolean IF_GONE=false;

	private KeyEvent mLastEvent = null;
	private KeyEvent mDownEvent = null;
	private int mStateFastSeek = STATE_FAST_SEEK_IDLE;

	private long speedTime =0;
	private RelativeLayout exitView;
	private ImageView fit_daka_gou1;
	private ImageView fit_daka_gou2;
	private ImageView fit_daka_gou3;

	private ImageView fit_daka_face1;
	private ImageView fit_daka_face2;
	private ImageView fit_daka_face3;

	private ImageView no;
	int time=0;

	private TextView fit_daka_name;
	private TextView fit_daka_time;
	private TextView dakaCol;

	private CircleImageView fit_daka_touxiang;
	private int biaoqing_num=3;
	String content_code="";
	String cate_code="";
	String userid="";
	String username="";
	String userurl="";
	private int mediaTime =0;
	private String colcumnTitle="";
	 public static Boolean IS_YULAN=false;
	int mTime=0;
	int endtime=0;
	private TextView timeStart;
	private TextView timeEnd;
	JSONArray arr_zhifubao=null;
	String orderInfo=null;
	private int currentPosition;
	private String playurl;
	Handler mHandler = new Handler(Looper.getMainLooper()) {


		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_PLAY_PROGRESS:
					//do something;
					if(progressBar.getVisibility()==View.VISIBLE) {
						try {
							if (mediaPlayer!=null&&mediaPlayer.getCurrentPosition() > 0) {
//											dialog2.cancel();
								progressBar.setVisibility(View.GONE);
							}
						}catch (IllegalStateException e){
							e.printStackTrace();
						}
					}
					if (mediaPlayer!=null&&mediaPlayer.getCurrentPosition()>(mediaPlayer.getDuration()-3000)){
						exitEndView.setVisibility(View.VISIBLE);
						mediaPlayer.pause();
						yesEnd.requestFocus();
						int time_num= mediaTime /1000;
						int min=time_num/60;
						int col=time_num*335/3600;
						dakaColEnd.setText(col+"");
					}
					if (mediaPlayer!=null&&mediaPlayer.getCurrentPosition()>20000&&!LoginActivity.IS_DINGGOU){
						try {
							all_visible();
							IF_GONE=true;
							playStat.setVisibility(View.VISIBLE);
							playStop.setVisibility(View.GONE);
							playStat.requestFocus();
						 	mediaPlayer.pause();
							currentPosition = mediaPlayer.getCurrentPosition();
							Log.d("@ricardo@",currentPosition+"  @ @ ");
							Behavior.onPlayContentStop(SimplePlayerActivity.this, mCateCode, mCateName, mContentCode, mTitle);
							creatAlertDialog_tuichu();
							mHandler.removeMessages(MSG_PLAY_PROGRESS);
						}catch (IllegalStateException e){
							e.printStackTrace();
						}

					}
					try{
					if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
						playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
						kaluli+=0.1;
						duration+=1;
						mediaTime =mediaPlayer.getCurrentPosition();
						int b1= mediaTime /1000;
						int s=b1%60;
						int m=b1/60;
						String ss=null;
						if(s<10){
							ss="0"+s;
						}else{
							ss=s+"";
						}
						timeStart.setText(m+":"+ss);
						SharedPreferences sp = SimplePlayerActivity.this.getSharedPreferences("wanba_config", Context.MODE_PRIVATE);
						SharedPreferences.Editor editor = sp.edit();
						editor.putInt("duration",duration);
						editor.apply();
//						UserCenterActivity.kaluli=kaluli;
						BigDecimal b  =   new BigDecimal(kaluli);
						float   f   =  b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
						int time_num= mediaTime /1000;
						int min=time_num/60;
						int col=time_num*335/3600;
						carlorie.setText(col+"");
					}else{

					}
				}catch (IllegalStateException e){
						e.printStackTrace();
				}



					mHandler.removeMessages(MSG_PLAY_PROGRESS);
					mHandler.sendEmptyMessageDelayed(MSG_PLAY_PROGRESS, 1000);
					break;

				case PLAY_MESSAGE:
					try{
						if(mediaPlayer != null && mediaPlayer.isPlaying()){
						if(!IF_GONE) {
							all_gone();
						}

					}else{

					}
					}catch (IllegalStateException e){
						e.printStackTrace();
					}
					mHandler.removeMessages(PLAY_MESSAGE);
					mHandler.sendEmptyMessageDelayed(PLAY_MESSAGE, 3500);
					IF_GONE=false;
					break;
			}
		}
	};
	String name;

	private ImageView yes;
	private RelativeLayout exitEndView;
	private ImageView yesEnd;
	private TextView dakaColEnd;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_simple_player);
		appName = getResources().getString(R.string.app_name);
		loading = getResources().getString(R.string.info_loading);

		exitInfo = getResources().getString(R.string.info_exit);

		Intent intent = getIntent();
		carlorie =(TextView)findViewById(R.id.kaluli_tv1);
		exitView =(RelativeLayout)findViewById(R.id.login_daka_relayout);
		exitEndView = ((RelativeLayout) findViewById(R.id.login_daka_relayout_end));
		yesEnd = ((ImageView) findViewById(R.id.login_daka_queding_end));
		yesEnd.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (mediaPlayer!=null){
					mediaPlayer.release();
					mediaPlayer=null;
				}
				finish();
			}
		});
		no =(ImageView)findViewById(R.id.login_daka_queding);
		yes = ((ImageView) findViewById(R.id.login_daka_quit));
		/*gif = (GifImageView) findViewById(R.id.gif);
		try {
			gifDrawable = new GifDrawable(getResources(), R.drawable.gg);
		} catch (IOException e) {
			e.printStackTrace();
		}
		gif.setImageDrawable(gifDrawable);*/


		if (intent != null) {
			if(intent.getStringExtra("cate_code")!=null) {
				mCateCode = Integer.parseInt(intent.getStringExtra("cate_code"));
			}
			if(intent.getStringExtra("content_code")!=null) {
				mContentCode = Integer.parseInt(intent.getStringExtra("content_code"));
			}
				mTitle = intent.getStringExtra("title");
				mCateName = intent.getStringExtra("cate_name");
			if (intent.getStringExtra("playurl")!=null){
				playurl=intent.getStringExtra("playurl");
			}
		}

		Log.d("ricardo",intent.getStringExtra("play_url")+"@@"+intent.getStringExtra("content_code")+"@@"+intent.getStringExtra("cate_code"));
		bofangView =(View)findViewById(R.id.bofang_view);
		playStat =(ImageView)findViewById(R.id.play_stat);
		playStop =(ImageView)findViewById(R.id.play_stop);
		playBack =(ImageView)findViewById(R.id.play_back);
		playGo =(ImageView)findViewById(R.id.play_go);

		surfaceView = (SurfaceView) findViewById(R.id.simple_video_view);
		final SurfaceHolder surfaceHolder = surfaceView.getHolder();
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		playprogressbar = (ProgressBar) findViewById(R.id.play_progressbar);
		timeStart = ((TextView) findViewById(R.id.time_tv1));
		timeEnd = ((TextView) findViewById(R.id.time_tv2));
		progressBar =(ProgressBar)findViewById(R.id.pro_mid);
		surfaceHolder.addCallback(new SurfaceHolder.Callback() {
			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				try {
				mediaPlayer = new WanbaMediaPlayer();
				mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
					@Override
					public void onPrepared(MediaPlayer mp) {
						Log.d("ricardo","pre");
						time=mediaPlayer.getDuration();
						mediaPlayer.seekTo(currentPosition);
						currentPosition=0;
						mediaPlayer.start();
						DataReport.ContentInformation(SimplePlayerActivity.this,"1200",mCateCode+"",mContentCode+"",mTitle,"0");

						if(speedTime >0){
							mediaPlayer.seekTo((int) speedTime);
						}
						Behavior.onPlayContentStart(SimplePlayerActivity.this, mCateCode, mCateName, mContentCode, mTitle);
						playprogressbar.setMax(mediaPlayer.getDuration());
						mTime=mediaPlayer.getDuration();
						mHandler.sendEmptyMessage(MSG_PLAY_PROGRESS);
						int b=time/1000;
						int s=b%60;
						int m=b/60;
						String ss=null;
						if(s<10){
							ss="0"+s;
						}else{
							ss=s+"";
						}
						timeEnd.setText(m+":"+ss);

					}
				});
				mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						isRunning = false;
						Behavior.onPlayContentStop(SimplePlayerActivity.this,mCateCode,mCateName,mContentCode,mTitle);
						DataReport.EventInformation(SimplePlayerActivity.this,"3300","000003","{\"contentcode\":"+mContentCode+",\"categorycode\":"+mCateCode+",\"duration\":"+mTime+"}");
						endtime=mTime;
						mediaPlayer.release();



						title = SimplePlayerActivity.this.getSharedPreferences("wanba_config", Context.MODE_PRIVATE).getString("title", null);

					}
				});

				mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
					@Override
					public void onBufferingUpdate(MediaPlayer mp, int percent) {
						playprogressbar.setSecondaryProgress((int) (mediaPlayer.getDuration() * ((float) percent / 100)));
					}
				});

				mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				mediaPlayer.setDisplay(surfaceHolder);

					final String[] playUrl = {SimplePlayerActivity.this.getIntent().getStringExtra("play_url")};
					colcumnTitle = SimplePlayerActivity.this.getIntent().getStringExtra("title_lanmu");
					content_code=SimplePlayerActivity.this.getIntent().getStringExtra("content_code");
					cate_code=SimplePlayerActivity.this.getIntent().getStringExtra("cate_code");
//					Toast.makeText(SimplePlayerActivity.this,title_lanmu,Toast.LENGTH_SHORT).show();
//			mediaPlayer.setDataSource(playUrl);

					mediaPlayer.setUrl(playurl, new WanbaMediaPlayer.OnCheckFinishCallback() {
						@Override
						public void onCheckFinish(boolean success) {

							mediaPlayer.prepareAsync();
							mediaPlayer.setVolume(0.5f, 0.5f);
//							mediaPlayer.start();

						}
					});

				} catch (IllegalStateException e){
					e.printStackTrace();
				}catch (Exception e) {
					mediaPlayer.reset();
				}
			}

			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

			}

			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				mHandler.removeMessages(MSG_PLAY_PROGRESS);
				Behavior.onPlayContentStop(SimplePlayerActivity.this, mCateCode, mCateName, mContentCode, mTitle);
				if (mediaPlayer != null) {
					try {
						mediaPlayer.release();
						mediaPlayer = null;
					}catch (IllegalArgumentException e){
						e.printStackTrace();
					}

				}
			}
		});


		playStat.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!mediaPlayer.isPlaying()) {
					IF_GONE=true;
					playStop.setVisibility(View.VISIBLE);
					playStat.setVisibility(View.GONE);
					playStop.requestFocus();
					mediaPlayer.start();
					Behavior.onPlayContentStart(SimplePlayerActivity.this, mCateCode, mCateName, mContentCode, mTitle);
				} else {

				}

			}
		});
		no.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				exitView.setVisibility(View.GONE);
			}
		});
		playStop.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				IF_GONE=true;
				if(mediaPlayer.isPlaying()) {
					playStat.setVisibility(View.VISIBLE);
					playStop.setVisibility(View.GONE);
					playStat.requestFocus();
					mediaPlayer.pause();
					Behavior.onPlayContentStop(SimplePlayerActivity.this, mCateCode, mCateName, mContentCode, mTitle);
				}
			}
		});
		playBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				IF_GONE=true;
				if(mediaPlayer.isPlaying()) {
					mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 10000);
				}else{
					speedTime -=10000;
					mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 10000);
					playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
				}
			}
		});
		playGo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				IF_GONE=true;
				if(mediaPlayer.isPlaying()) {
					mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 10000);
				}else{
					speedTime +=10000;
					mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 10000);
					playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
				}
			}
		});



		try {
			yes.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					post_shangchuan();
					Behavior.onEvent(SimplePlayerActivity.this, 3050005, "播放页面打卡");
					exitView.setVisibility(View.GONE);
					DataReport.PageRetreat(SimplePlayerActivity.this, "2100", "300005");
					if(endtime!=0) {
						DataReport.ContentInformation(SimplePlayerActivity.this, "2200", mCateCode + "", mContentCode + "", mTitle, mTime+ "");
						int time_num=mTime/1000;
						int min=time_num/60;
						final int col=time_num*335 / 3600;
						DataReport.EventInformation(SimplePlayerActivity.this,"3300","000002","{\"emoji\":"+biaoqing_num+",\"duration\":"+mTime +",\"cal\":"+col+"}");

					}else {
						DataReport.ContentInformation(SimplePlayerActivity.this, "2200", mCateCode + "", mContentCode + "", mTitle, mediaPlayer.getCurrentPosition()  + "");
						int time_num=mediaPlayer.getDuration()/1000;
						int min=time_num/60;
						final int col=time_num*335 / 3600;
						DataReport.EventInformation(SimplePlayerActivity.this,"3300","000002","{\"emoji\":"+biaoqing_num+",\"duration\":"+mediaPlayer.getCurrentPosition() +",\"cal\":"+col+"}");
					}
					if (mediaPlayer!=null){
						mediaPlayer.release();
						mediaPlayer=null;
					}
					finish();
				}
			});
		}catch (IllegalStateException e){
			e.printStackTrace();
		}catch (Exception e){
			e.printStackTrace();
		}


		/*fit_daka_name=(TextView)findViewById(R.id.login_daka_name);
		fit_daka_time=(TextView)findViewById(R.id.login_daka_time);*/
		dakaCol =(TextView)findViewById(R.id.login_daka_col);
		dakaColEnd = ((TextView) findViewById(R.id.login_daka_col_end));
		//fit_daka_touxiang=(CircleImageView)findViewById(R.id.login_daka_touxiang);

		RequestQueue rq1 = Volley.newRequestQueue(this.getApplicationContext());
		JsonObjectRequest request1 = new JsonObjectRequest("http://61.191.46.214:8088/wanba/photo_ajax.jsp?userId="+ Util.getDeviceId(this), null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject jsonObject) {
						try {
							JSONArray arr=jsonObject.getJSONArray("userList");
							JSONObject obj=arr.getJSONObject(0);
							String iv_url=obj.getString("portraitUrl");
							userurl=obj.getString("portraitUrl");
							userid=obj.getString("userId");
							//fit_daka_name.setText(obj.getString("userName"));
							username=obj.getString("userName");
							RequestQueue mQueue = Volley.newRequestQueue(SimplePlayerActivity.this);
							ImageRequest imageRequest = new ImageRequest(
									iv_url,
									new Response.Listener<Bitmap>() {
										@Override
										public void onResponse(Bitmap response) {
											//fit_daka_touxiang.setImageBitmap(response);
										}
									}, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
								@Override
								public void onErrorResponse(VolleyError error) {
//                                    erweima_login.setImageResource(R.drawable.default_image);
								}
							});
							mQueue.add(imageRequest);
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError volleyError) {
			}
		}

		);
		request1.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
		rq1.add(request1);
		mHandler.sendEmptyMessage(PLAY_MESSAGE);

	}

	/**
	 * 向指定的服务器报告视频播放信息
	 * 暂时没有真正发送请求
	 * 如果需要请将加入队列的代码注释去掉
	 */
	public void jsonReport(String url) {
		JSONObject jsonRequest = new JSONObject();
		try {
			jsonRequest.put("cate_code", getIntent()
					.getStringExtra("cate_code"));
			jsonRequest.put("media_code",
					getIntent().getStringExtra("media_code"));
			jsonRequest.put("play_url", getIntent().getStringExtra("play_url"));
			jsonRequest.put("title_lanmu", getIntent().getStringExtra("title_lanmu"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		JsonObjectRequest request = new JsonObjectRequest(url, jsonRequest,
				null, null);
		// AppUtil.getInstance(SimplePlayerActivity.this).getRequestQueue()
		// .add(request);

	}

	public void exitPlay() {
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			Toast.makeText(this, exitInfo, Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		} else {
			kaluli=0;
			this.finish();
		}
	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			// 判断2秒内是否重复点击返回键
			String yulan = getIntent().getStringExtra("abc");
			name=yulan+"@@";
				jsonReport(getResources().getString(R.string.end_report_url));
			if (name.equals("sim@@")){
				//Toast.makeText(getApplicationContext(),"aaaaaa",Toast.LENGTH_LONG).show();
				Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
				startActivity(intent);
				if (mediaPlayer!=null){
					mediaPlayer.release();
					mediaPlayer=null;
				}
				finish();
			}else if (name.equals("null@@")){
				//Toast.makeText(getApplicationContext(),"bbbbbb",Toast.LENGTH_LONG).show();
				if(exitView.getVisibility()==View.GONE){
					exitView.setVisibility(View.VISIBLE);
					//fit_daka_face3.requestFocus();
					yes.requestFocus();
					playStat.setFocusable(false);
					playStop.setFocusable(false);
					playBack.setFocusable(false);
					playGo.setFocusable(false);
					int time_num= mediaTime /1000;
					int min=time_num/60;
					int col=time_num * 335 / 3600;
					//fit_daka_time.setText(min+" min");
					dakaCol.setText(col+" col");
				}else {
					exitView.setVisibility(View.GONE);
					exitEndView.setVisibility(View.GONE);
					playStat.setFocusable(true);
					playStop.setFocusable(true);
					playBack.setFocusable(true);
					playGo.setFocusable(true);
				}
			}
			return true;
		}
		else if((keyCode == KeyEvent.KEYCODE_DPAD_LEFT)){
			if((playBack.getVisibility()==View.INVISIBLE)){
				all_visible();
				IF_GONE=true;
				return true;
			}else {
				if (mStateFastSeek == STATE_FAST_SEEK_IDLE) {
					IF_GONE = true;
					mStateFastSeek = STATE_FAST_SEEK_PREPARED;

					mDownEvent = event;
				} else if (mStateFastSeek == STATE_FAST_SEEK_PREPARED) {

					final long deltaEventTime = event.getEventTime() - mDownEvent.getDownTime();
					if (deltaEventTime > 300) {
						mStateFastSeek = STATE_FAST_SEEK_START;
						mLastEvent = event;
						Log.d("KeyEvent", "@@@ onKeyDown at " + event.getEventTime());
						if(mediaPlayer.isPlaying()) {
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 2000);
						}else{
							speedTime -=2000;
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 2000);
							playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
						}
						IF_GONE = true;
					}
				} else if (mStateFastSeek == STATE_FAST_SEEK_START) {
					final long deltaEventTime = event.getEventTime() - mLastEvent.getEventTime();
					if (deltaEventTime > 100) {
						mLastEvent = event;
						Log.d("KeyEvent", "@@@ onKeyDown at " + event.getEventTime());
						if(mediaPlayer.isPlaying()) {
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 2000);
						}else{
							speedTime -=2000;
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 2000);
							playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
						}
						IF_GONE = true;
					}
				}

				return super.onKeyDown(keyCode, event);
			}
		}
		else if((keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)){
			if((playBack.getVisibility()==View.INVISIBLE)){
				all_visible();
				IF_GONE=true;
				return true;
			}else {
				if (mStateFastSeek == STATE_FAST_SEEK_IDLE) {
					IF_GONE = true;
					mStateFastSeek = STATE_FAST_SEEK_PREPARED;
					mDownEvent=event;
				} else if (mStateFastSeek == STATE_FAST_SEEK_PREPARED) {

					final long deltaEventTime = event.getEventTime() - mDownEvent.getDownTime();
					if (deltaEventTime > 300) {
						mStateFastSeek = STATE_FAST_SEEK_START;
						mLastEvent = event;
						Log.d("KeyEvent", "@@@ onKeyDown at " + event.getEventTime());
						if(mediaPlayer.isPlaying()) {
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 2000);
						}else{
							speedTime +=2000;
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 2000);
							playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
						}
						IF_GONE = true;
					}
				} else if (mStateFastSeek == STATE_FAST_SEEK_START) {
					final long deltaEventTime = event.getEventTime() - mLastEvent.getEventTime();
					if (deltaEventTime > 100) {
						mLastEvent = event;
						Log.d("KeyEvent", "@@@ onKeyDown at " + event.getEventTime());
						if(mediaPlayer.isPlaying()) {
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 2000);
						}else{
							speedTime +=2000;
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 2000);
							playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
						}
						IF_GONE = true;
					}
				}
				return super.onKeyDown(keyCode, event);
			}
		}
		else {
			if((playBack.getVisibility()==View.INVISIBLE)){
				all_visible();
				IF_GONE=true;
				return true;
			}else {
				IF_GONE=true;
				return super.onKeyDown(keyCode, event);
			}
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if((keyCode == KeyEvent.KEYCODE_DPAD_LEFT)) {
			if (mStateFastSeek == STATE_FAST_SEEK_START) {
				mStateFastSeek = STATE_FAST_SEEK_IDLE;
				mLastEvent = null;
				mDownEvent = null;
			}
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	public void onPrepared(MediaPlayer mp) {

	}


	@Override
	public boolean onInfo(MediaPlayer mp, int what, int extra) {
		return true;
	}


	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
//		mp.release();
		kaluli=0;
		finish();
		return false;
	}
	public void all_gone(){

		bofangView.setVisibility(View.INVISIBLE);
		playStat.setVisibility(View.INVISIBLE);
		playStop.setVisibility(View.INVISIBLE);
		playBack.setVisibility(View.INVISIBLE);
		playGo.setVisibility(View.INVISIBLE);
		timeStart.setVisibility(View.INVISIBLE);
		timeEnd.setVisibility(View.INVISIBLE);
		playprogressbar.setVisibility(View.INVISIBLE);
	}
	public void all_visible(){
		bofangView.setVisibility(View.VISIBLE);
		playStop.setVisibility(View.VISIBLE);
		playBack.setVisibility(View.VISIBLE);
		playGo.setVisibility(View.VISIBLE);
		timeStart.setVisibility(View.VISIBLE);
		timeEnd.setVisibility(View.VISIBLE);
		playprogressbar.setVisibility(View.VISIBLE);
	}
	private AlertDialog myDialog = null;

	@Override
	protected void onResume() {
		super.onResume();
		Behavior.onPageResume(this, 300001, "播放页面");
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mediaPlayer!=null){
			mediaPlayer.release();
			mediaPlayer=null;
		}

		Behavior.onPagePause(this, 300001, "播放页面");
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mediaPlayer!=null){
			mediaPlayer.release();
			mediaPlayer=null;
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		if(IS_YULAN){
			DataReport.PageRetreat(SimplePlayerActivity.this, "1100", "300006");
		}else{
			DataReport.PageRetreat(SimplePlayerActivity.this, "1100", "300005");
		}

	}

	private void post_shangchuan(){
		RequestQueue requestQueue = Volley.newRequestQueue(SimplePlayerActivity.this);
		String url= "http://61.191.46.214:8087/checkin/add";
		StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST,url,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						Log.e("zzzzz",response);
					}
				}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				error.printStackTrace();
			}
		}) {
			@Override
			protected Map<String, String> getParams() {
				//在这里设置需要post的参数
				Map<String, String> map = new HashMap<String, String>();
				map.put("deviceid", Util.getDeviceId(SimplePlayerActivity.this));
				map.put("emoji",biaoqing_num+"");
				map.put("duration", mediaTime /1000+"");
				map.put("region","23");
				map.put("title",colcumnTitle);
				map.put("contentcode", content_code);
				map.put("category", cate_code);
				map.put("wxnickname",username);
				map.put("wxuserid",userid);
				map.put("wxportrait",userurl);
				return map;
			}
		};
		stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
		requestQueue.add(stringRequest);
	}
	private void creatAlertDialog_tuichu() {

		if (hasWindowFocus()){
			if (myDialog==null){
				myDialog = new AlertDialog.Builder(SimplePlayerActivity.this).create();

				myDialog.show();

				myDialog.getWindow().setContentView(R.layout.diolag_queding);

				myDialog.getWindow()
						.findViewById(R.id.no_iv)
						.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {

								myDialog.dismiss();

							}

						});
				myDialog.getWindow()
						.findViewById(R.id.yes_iv)
						.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								myDialog.dismiss();
								chanpinbao();
								if (mediaPlayer!=null){
									mediaPlayer.release();
									mediaPlayer=null;
								}
							}

						});
			}
		}
	}

	private void chanpinbao(){
		RequestQueue rq_2 = Volley.newRequestQueue(getApplicationContext());
		final JsonObjectRequest request_2 = new JsonObjectRequest("http://61.191.46.214:8087/getapi/common/subjects/31259d2c48bec6a1ba589360c748e132?flavor="+ Product.flavor, null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject jsonObject) {
						try {
							JSONObject obj=jsonObject.getJSONObject("data");
							JSONArray arr=obj.getJSONArray("list");
							arr_zhifubao=arr;
							//Toast.makeText(getApplicationContext(),obj+"@@",Toast.LENGTH_LONG).show();
							dingdanhao();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError volleyError) {
				Toast.makeText(getApplicationContext(),"请求产品包超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

			}
		}

		) {
			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {
				HashMap<String, String> headers = new HashMap<String, String>();
				PackageInfo pi= null;
				try {
					pi = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
					headers.put("accept", "applicationnd.wanba.wanbatv.com.wudao;version="+pi.versionName);
					headers.put("app_version", pi.versionName);
					headers.put("app_package_name",pi.packageName);
				} catch (PackageManager.NameNotFoundException e) {
					e.printStackTrace();
				}


				// MyLog.d(TAG, "headers=" + headers);
				return headers;
			}
		};
		request_2.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));

		rq_2.add(request_2);
	}
	private  void dingdanhao(){

		try {
			JSONObject obj = arr_zhifubao.getJSONObject(0);
			final   String subject=obj.getString("subject");
			final   String subjectid=obj.getString("subjectId");
			final   String price=obj.getString("price");
			//Toast.makeText(getApplicationContext(),obj+"==",Toast.LENGTH_SHORT).show();
			RequestQueue requestQueue = Volley.newRequestQueue(SimplePlayerActivity.this);
			String url="http://61.191.46.214:8087/postapi/common/wpay/getorder";
			StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST,url,
					new Response.Listener<String>() {

						@Override
						public void onResponse(String response) {

							try {

								JSONObject obj_zhifubao = (JSONObject) new JSONTokener(response).nextValue();
								//Toast.makeText(getApplicationContext(),obj_zhifubao+"  @  @  "+Util.getDeviceId(getApplicationContext()),Toast.LENGTH_LONG).show();
								JSONObject oobj=obj_zhifubao.getJSONObject("data");
								String order=oobj.getString("order");
								orderInfo="orderId="+order+"|itvAccount="+ AppUtil.STB.UserID+"|productId=zg_wanba"+"|price=1500";
								orderInfo=jiami(orderInfo);
								Log.d("@ricardo@", "get subject "+obj_zhifubao);
								Log.d("@ricardo@",AppUtil.STB.Sn+"@@"+AppUtil.STB.IP+"@@"+AppUtil.STB.UserID);
								ItvPayTask itvPayTask = new ItvPayTask(SimplePlayerActivity.this);
								HashMap<String, String> data = new HashMap<String, String>();
								data.put(ItvPayTask.NET_IP, "61.191.45.118");//访问地址ip 测试ip为61.191.45.116 正式为//61.191.45.118
								data.put(ItvPayTask.NET_PORT, "7002");//访问地址端口
								data.put(ItvPayTask.DEVICEMODEL, AppUtil.STB.Model);//机顶盒信息
							//	data.put(ItvPayTask.RETURNURL, "http://61.191.46.214:8087/getapi/common/wpay/result/ahpay/");//同步返回地址
								data.put(ItvPayTask.NOTIFYURL, "http://172.16.33.228:8087/postapi/common/wpay/paynotify/ahpay/"+AppUtil.STB.UserID);//异步通知地址
								data.put(ItvPayTask.DEVICETYPE, "hd");//机顶盒信息
								data.put(ItvPayTask.USERAGENT, "wanba");//机顶盒信息
								data.put(ItvPayTask.DEVICESERIALNO, AppUtil.STB.Sn);//机顶盒信息
								data.put(ItvPayTask.IP, AppUtil.STB.IP);//机顶盒信息
								data.put(ItvPayTask.ORDERINFO, orderInfo);//订单信息
								data.put(ItvPayTask.PROVIDERID, "shzg");//供应商id
								itvPayTask.pay(data);

							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					}, new Response.ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError error) {
					Toast.makeText(getApplicationContext(),"请求订单号超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

					error.printStackTrace();
				}
			}) {
				@Override
				public Map<String, String> getHeaders() throws AuthFailureError {
					HashMap<String, String> headers = new HashMap<String, String>();
					PackageInfo pi= null;
					try {
						pi = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
						headers.put("accept", "applicationnd.com.wanbatv.wanba.jianshencao;version="+pi.versionName);
						headers.put("app_version", pi.versionName);
						headers.put("app_package_name",pi.packageName);
					} catch (PackageManager.NameNotFoundException e) {
						e.printStackTrace();
					}


					// MyLog.d(TAG, "headers=" + headers);
					return headers;
				}
				@Override
				public String getBodyContentType() {
					return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
				}
				@Override
				protected Map<String, String> getParams() {
					//在这里设置需要post的参数
					HashMap<String, String> params = new HashMap<String, String>();
					params.put("partner","");
					params.put("subject", subject);
					params.put("subjectid",subjectid);
					params.put("price",price);
					params.put("provider","ahpay");
					params.put("stb", Util.getDeviceId(getApplicationContext()));
					params.put("flavor", Product.flavor);

					return params;
				}
			};
			stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
			requestQueue.add(stringRequest);
		} catch (JSONException e) {
			Toast.makeText(getApplicationContext(),"eeeee",Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}
	private  String jiami(String orderInfo){
//        String msg = "使用3DES对数据进行加密";
//        byte[] secretArr = DES3Utils.encryptMode(msg.getBytes());
//        String jiami=Base64.encodeToString(secretArr,Base64.DEFAULT);
//        String res = null;
//        try {
//            res = new String(DES3Utils.decryptMode(Base64.decode(jiami, Base64.DEFAULT)), "utf-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        Log.e("jiami","3des result " + msg.equals(res) + " res " + res + ", encrypt " + jiami);

		String jiami= Crypto.TripleDES.encrypt(orderInfo,"26f545c0d092463185acdd3e2c73fdda");
//        String jiami=Crypto.TripleDES.decrypt(jiami,"36161889369a412b923af17dafb0fe88");
		Log.e("jiami",jiami);
//        Log.e("jiemi",jiemi);
		return jiami;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == ItvPayTask.REQUEST_ITYPAY&&resultCode==ItvPayTask.RESULT_ITVPAY) {
			String result = data.getStringExtra("result");
			//Toast.makeText(getApplicationContext(),result+"",Toast.LENGTH_LONG).show();
			try {
				JSONObject obj=(JSONObject) new JSONTokener(result).nextValue();
				if(!obj.getString("tradeInfo").equals("") ){
					LoginActivity.IS_DINGGOU =true;
					all_visible();
					playStat.setVisibility(View.GONE);
				}else{
					all_visible();
					playStat.setVisibility(View.GONE);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			Log.e("huidiao",result);
		}
	}
}
